/**
 * 
 */
package com.mobile2you.nci.android.data;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;

import android.content.Context;

import com.mobile2you.nci.android.R;
import com.mobile2you.nci.android.domain.Annuaires;
import com.mobile2you.nci.android.domain.Centres;
import com.mobile2you.nci.android.domain.News;
import com.mobile2you.nci.android.domain.Services;

/**
 * @author JBromo
 * 
 */
public class InitialDataLoader {

	public static List<Annuaires> getAnnuaire(Context context) {
		try {
			String data = getDataFromRaw(context, R.raw.annuaire);
			JSONArray jsonArray = new JSONArray();
			if (data != null) {
				jsonArray = new JSONArray(data);
			}
			if (jsonArray != null && jsonArray.length() > 1) {
				SqlHelper.getInstance(context).saveAnnuaire(jsonArray);
			}
			return DataParseur.parseAnnuaire(new JSONArray(data));
		} catch (Exception e) {
			e.printStackTrace();
			return new ArrayList<Annuaires>();
		}

	}

	public static List<Centres> getCentres(Context context) {
		try {
			String data = getDataFromRaw(context, R.raw.centres);
			JSONArray jsonArray = new JSONArray();
			if (data != null) {
				jsonArray = new JSONArray(data);
			}
			if (jsonArray != null && jsonArray.length() > 1) {
				SqlHelper.getInstance(context).saveCentres(jsonArray);
			}

			return DataParseur.parseCentres(new JSONArray(data));
		} catch (Exception e) {
			return new ArrayList<Centres>();
		}

	}

	private static String getDataFromRaw(Context context, int idraw) {
		try {
			InputStream stream = context.getResources().openRawResource(idraw);
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					stream));
			String line = null;
			StringBuilder builder = new StringBuilder();
			while ((line = reader.readLine()) != null) {
				builder.append(line);
			}
			return builder.toString();

		} catch (Exception e) {
			return null;

		}
	}

	public static List<News> getNews(Context context) {
		try {
			String data = getDataFromRaw(context, R.raw.news);
			return DataParseur.parseNews(new JSONArray(data));
		} catch (Exception e) {
			return new ArrayList<News>();
		}

	}

	public static List<Services> getServices(Context context) {
		try {
			String data = getDataFromRaw(context, R.raw.services);
			return DataParseur.parseServices(new JSONArray(data));
		} catch (Exception e) {
			return new ArrayList<Services>();
		}

	}

	/**
	 * 
	 */
	private InitialDataLoader() {
		super();
		// TODO Auto-generated constructor stub
	}
}
